import paramiko

from typing import Annotated
from datetime import datetime, timedelta

from fastapi import FastAPI, Depends, Form, HTTPException, status, Query

from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.responses import HTMLResponse
from passlib.context import CryptContext

import jwt

from db.util import JsonDatabase


app = FastAPI()

user_db = JsonDatabase("user.json")
server_db = JsonDatabase("server.json")



#region 注册与登录

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_schema = OAuth2PasswordBearer(tokenUrl="/token")
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
ALGORITHM = "HS256"  # 用于签名的算法
ACCESS_TOKEN_EXPIRE_MINUTES = 120  # 令牌过期时间

def create_jwt_token(data:dict, expires: timedelta | None = None):
    data_encode = data.copy()
    if expires:
        delta = datetime.now() + expires
    else:
        delta = datetime.now() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    data_encode.update({"exp":delta})
    print(data_encode)
    return jwt.encode(data_encode, SECRET_KEY, ALGORITHM)

@app.post("/users")
def register(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
    username = form_data.username
    password = pwd_context.hash(form_data.password)
    if user_db.select('users',{"username":username}):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail="username exists"
        )
    user_db.insert('users', {"username": username, "password": password})
    return {"status":"success","data":username}

@app.post("/token")
def login(username: Annotated[str, Form()], password: Annotated[str, Form()]):
    print(username)
    if not (
        len(user_db.select("users",{"username":username})) != 0 
        and username == user_db.select("users",{"username":username})[0].get("username")
        and pwd_context.verify(password, user_db.select("users",{"username":username})[0].get('password'))
    ):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail="login failed"
        )
    # return {"access_token": username, "token_type": "Bearer"}
    jwt = create_jwt_token({"sub":username})
    return {"access_token": jwt, "token_type": "Bearer"}
    

#endregion 注册与登录

@app.get("/serverList")
def get_server_list(name:Annotated[str, Query()]):
    if name == 'true':
        return[
            {"name":'test1','id':1},
            {"name":'test2','id':2},
            {"name":'test3','id':3},
            {"name":'test4','id':4},
        ]
    return {"1":"1"}



@app.post('/log')
def post_log( data):
    server_db.insert('123',data)
    return {"status":"success","data":{'id':id}}



# @app.post("/terminal")
# async def execute_command(host: str, username: str, password: str, command: str, port: int=22):
#     try:
#         # 创建 SSH 对象
#         ssh = paramiko.SSHClient()
#         # 允许连接不在 know_hosts 文件中的主机
#         ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#         # 连接服务器
#         ssh.connect(hostname=host, port=port, username=username, password=password)
#         # 执行命令
#         stdin, stdout, stderr = ssh.exec_command(command)
#         # 获取命令结果
#         result = stdout.read().decode()
#         # 获取错误信息
#         error = stderr.read().decode()
#         # 关闭连接
#         ssh.close()
#         if error:
#             return {"status": "error", "message": error}
#         return {"status": "success", "result": result}
#     except Exception as e:
#         return {"status": "error", "message": str(e)}
    
